package com.huluobo.kotlinim2006a

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.SoundPool
import android.os.Build
import androidx.annotation.RequiresApi
import com.huluobo.kotlinim2006a.adapter.EMMessageListenerAdapter
import com.huluobo.kotlinim2006a.ui.activity.ChatActivity
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMOptions
import com.hyphenate.chat.EMTextMessageBody

/**
 * Created by lc on 2023/2/2.
 */
class IMApplication : Application() {
    companion object {
        lateinit var instance: IMApplication
        //因为伴生函数类似于静态代码块,在类被创建时调用,此时还有没有Application的生命周期(onCreate)
        //也就是会在onCreate之前调用,这样肯定会产生空指针
        //使用lateinit ,则会在onCreate
    }

    //声音池
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    val soundPool: SoundPool = SoundPool.Builder().setMaxStreams(10).build()

    //应用处于前台的音乐文件
    val duan by lazy {
        soundPool.load(instance, R.raw.duan, 0)
    }

    //应用处于后台的音乐文件
    val yulu by lazy {
        soundPool.load(instance, R.raw.yulu, 0)
    }

    private val messageListener = object : EMMessageListenerAdapter() {
        override fun onMessageReceived(messages: MutableList<EMMessage>?) {
            //判断当前应用处于前台还是后台
            if (isForeground()) {
                //(播放的文件,左声道,右声道,播放优先级,循环模式,播放速率)
                soundPool.play(duan, 1f, 1f, 0, 0, 1f)
            } else {
                soundPool.play(yulu, 1f, 1f, 0, 0, 1f)
                //当应用处于后台位置时,接受到消息需要弹出通知
                showNotification(messages)
            }
        }
    }

    private fun showNotification(messages: MutableList<EMMessage>?) {
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        messages?.forEach {
            var contentText = "非文本消息"
            if (it.type == EMMessage.Type.TXT) {
                contentText = (it.body as EMTextMessageBody).message
            }//[图片][视频][表情]

            //负责跳转到聊天页面
            val intent = Intent(this, ChatActivity::class.java)
            intent.putExtra("username", it.conversationId()) //打开聊天页面必须要传递一个username,否则找不到聊天的对象

            val taskStackBuilder =
                TaskStackBuilder.create(this).addParentStack(ChatActivity::class.java)
                    .addNextIntent(intent)//首先要跳转到mainActivity,再跳转到ChatActivity

            val pendingIntent =
                taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)

            val notification = Notification.Builder(this)
                .setContentTitle(getString(R.string.receive_new_message))//通知的标题
                .setContentText(contentText)//通知的内容
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.avatar1))//通知中的大图标
                .setSmallIcon(R.mipmap.ic_contact)//状态栏上的小图标
                .setContentIntent(pendingIntent)//点击通知跳转的intent,使用pendingIntent可以连续跳转
                .setAutoCancel(true)//设置自动回弹
                .setFullScreenIntent(pendingIntent, true)//设置当有其他app处于全屏状态时,当前app通知的优先级
                .build()

            notificationManager.notify(1, notification)
        }
    }

    //判断应用是否在前台
    private fun isForeground(): Boolean {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (runningAppProcess in activityManager.runningAppProcesses) {
            //找到当前运行的app的进程
            //判断当前app的运行关键级是否等于处于前台的关键级
            return runningAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
        }
        return false
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        val options = EMOptions()
        options.appKey = "moroks#kotlinim1911a2";
        EMClient.getInstance().init(this, options)

        EMClient.getInstance().chatManager().addMessageListener(messageListener)

        soundPool.play(duan, 1f, 1f, 0, 0, 1f)
        soundPool.play(yulu, 1f, 1f, 0, 0, 1f)
    }
}